const { now } = require("mongoose");
const { Article, User } = require("../model");
const ObjectId = require("mongodb").ObjectId;
const moment = require("moment");

//创建文章
exports.createArticle = async (req, res, next) => {
  try {
    console.log(req.body, "----reqqqq");
    const article = new Article(req.body.article);
    // console.log(article, "----hahahah");
    // article.author = req.user._id;
    // article.populate("author");
    // article.authorAvatarUrl = req.user.avatarUrl;
    // article.authorName = req.user.nickName;
    await article.save();
    console.log(article, "-----art");
    res.status(201).json({
      article,
      // token: 'tempToken',
      // refreshToken: 'tempRefreshToken',
    });
  } catch (err) {
    // console.log(err);

    next(err);
  }
};

// 获取选中文章信息
exports.getArticle = async (req, res, next) => {
  try {
    // console.log(req)
    // const article = await await Article.findById(req.parmas.articleId);
    const article = await Article.find({
      _id: req.params.articleId,
    }).populate("author"); //添加一个映射 具体看 /model/article
    if (!article) {
      return res.status(404).end();
    } else {
      console.log(article, "----art");
    }
    res.status(200).json({
      article,
    });
  } catch (err) {
    console.log(req.params);
    next(err);
  }
};

// 获取文章列表
exports.getArticles = async (req, res, next) => {
  try {
    // res.send("getArticle");
    // console.log(req);
    const { limit = 20, offset = 0, tag, author, title } = req.query;

    const filter = {};

    if (tag) {
      //如果携带的参数中有 tag 的话
      //那么就会在文章列表中筛选出有符合条件的tag的文章
      filter.tagList = tag;
    }

    if (author) {
      //如果携带的参数中有 author 的话
      //那么就会在文章列表中筛选出对应作者的文章
      const user = await User.findOne({
        userName: { $regex: new RegExp(author, "i") },
      });
      console.log(user);
      // console.log(ObjectId(user._id));
      filter.author = user ? user._id : null;
      // console.log(filter);
    }

    if (title) {
      const article = await Article.findOne({
        title: { $regex: new RegExp(title, "i") },
      });
      filter.title = article ? article.title : null;
    }

    const articles = await Article.find(filter)
      .skip(Number.parseInt(offset))
      .limit(Number.parseInt(limit)); //skip表示跳过多少条数据 limit表示取多少条数据
    const articlesCount = await Article.countDocuments();
    res.status(200).json({
      articles,
      articlesCount,
    });
  } catch (error) {
    next(error);
  }
};

//文章点赞
// exports.likeArticle = async (req, res, next) => {
//   try {
//     const { articleId } = req.body;
//     const article = await Article.findOne({
//       _id: articleId,
//     });

//     if (article.favourite) {
//       article.favouritesCount--;
//     } else {
//       article.favouritesCount++;
//     }
//     article.favourite = !article.favourite;
//     await article.save();
//     res.status(200).json({
//       article,
//     });
//   } catch (err) {
//     // console.log(req.params);
//     next(err);
//   }
// };

exports.likeArticle = async (req, res, next) => {
  try {
    console.log(req.user, "----req.user");
    const articleId = req.params.articleId; // 或 req.body.articleId，取决于你发送数据的方式
    const userId = req.user._id; // 假设已通过验证中间件得到用户信息

    const article = await Article.findById(articleId);
    if (!article) {
      return res.status(404).json({ message: "文章不存在" });
    }

    // 检查用户是否已经点赞
    if (article.favouriteUsers.includes(userId)) {
      // 如果已经点赞，则取消点赞
      article.favouriteUsers.remove(userId);
      article.favouritesCount -= 1;
    } else {
      // 否则添加点赞
      article.favouriteUsers.push(userId);
      article.favouritesCount += 1;
    }

    await article.save();

    res.status(200).json({
      articleId: article._id,
      favouriteUsers: article.favouriteUsers,
      favouritesCount: article.favouritesCount,
    });
  } catch (err) {
    next(err);
  }
};

// 添加评论
exports.addComments = async (req, res, next) => {
  try {
    let comment = req.body.comment;
    let articleId = req.body.articleId;
    console.log(req.body, "----req.body");
    const article = await Article.findOne({
      _id: articleId,
    });
    if (article) {
      article.comments.unshift(comment);
      await article.save();
    }
    res.status(200).json({
      article: article,
    });
  } catch (err) {
    next(err);
  }
};

exports.deleteArticle = async (req, res, next) => {
  try {
    const { articleId } = req.body;
    console.log(articleId);
    const article = await Article.findOne({ _id: articleId });
    console.log(article, "-----art");
    if (article) {
      console.log(article);
      article.deleteOne({ _id: articleId });
      await article.save();
      res.status(200).json({
        statusCode: 200,
        request: "ok",
        errMsg: "文章删除成功",
      });
    } else {
      res.status(404).json({
        statusCode: 404,
        request: "fail",
        errMsg: "您请求的文章不存在～",
      });
    }
  } catch (err) {
    next(err);
  }
};
